package com.likeyoudo.common.utils;

import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.ToastUtils;
import com.likeyoudo.common.BaseFragment;

import java.util.List;

/**
 * @author LikeYouDo
 * @date 2023/12/26 15:31
 */
public class CommonUtils {
    public static int findFragmentIndexByClass(@NonNull List<BaseFragment> fragments, @NonNull Class<? extends BaseFragment> clazz) {
        for (BaseFragment fragment : fragments) {
            if (fragment != null && fragment.getClass().equals(clazz)) {
                return fragments.indexOf(fragment);
            }
        }
        // 默认返回第0页,并且发出Toast
        ToastUtils.showShort("页面跳转失败,请联系作者");
        return 0;
    }

    /**
     *  取消焦点并且关闭软键盘
     * @param context
     */
    public static void clearFocus(Context context) {
        if (context != null) {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            View view = ((Activity) context).getWindow().getCurrentFocus(); // 获取当前获得焦点的视图
            if (view != null && imm.isActive(view)) { // 如果有视图正在获得焦点且键盘已打开
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0); // 隐藏键盘
                view.clearFocus(); // 清除焦点
            }
        }
    }

}
